package com.link2room.blaster.service.impl;

import com.link2room.blaster.dto.inMail.WebSocketDto;
import com.link2room.blaster.service.IWebSocketSessionCacheService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * Created by LN on 2017/6/27.15:44
 */
@Component("webSocketSessionCacheService")
public class WebSocketSessionCacheServiceImpl implements IWebSocketSessionCacheService {
    /**
     * 存放webSocket session内容 key ：adminUserCode  value: Session.Id
     */
    private static Map<String,Set<String>> sessionIdMap = new ConcurrentHashMap<>();
    /**
     * 存放所有的会话
     */
    private static Map<String,WebSocketDto> webSocketMap = new ConcurrentHashMap<>();

    @Override
    public void cacheSession(String userCode, WebSocketDto session) {
        synchronized (userCode){
            Set<String> sessionIdSet = sessionIdMap.get(userCode);
            if(sessionIdSet == null){
                sessionIdSet = new CopyOnWriteArraySet();
            }
            sessionIdSet.add(session.getSession().getId());
            sessionIdMap.put(userCode,sessionIdSet);
            webSocketMap.put(session.getSession().getId(),session);
        }
    }

    @Override
    public void remove(String sessionId) {
        synchronized (sessionId){


            WebSocketDto dto = webSocketMap.get(sessionId);
            if(dto == null){
                return;
            }

            String userCode = dto.getUserCode();
            Set<String> idSet = sessionIdMap.get(userCode);
            if(idSet != null){
                idSet.remove(sessionId);
            }
            webSocketMap.remove(sessionId);
        }
    }

    @Override
    public List<WebSocketDto> getSession(String userCode) {
        Set<String> idSet = sessionIdMap.get(userCode);
        if(CollectionUtils.isEmpty(idSet)){
            return Collections.emptyList();
        }
        return idSet.stream().map(id->webSocketMap.get(id)).collect(Collectors.toList());
    }
}
